package com.shuyihui.databindinglib;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 使用 DataBind 并使用ViewModel
 * @param <VDB>
 * @param <VM> 继承BaseViewModel
 */
public abstract class BaseMActivity<VDB extends ViewDataBinding,VM extends BaseViewModel> extends BaseDActivity<VDB> {
    protected VM mViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        createViewModel();
        super.onCreate(savedInstanceState);
    }

    public void createViewModel() {
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
                mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
            }
        }
    }
}
